How to write window function in SQL